package com.free.utils.crypt;


import com.free.exception.SystemRuntimeException;
import com.free.utils.CharsetUtils;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;


public class MD5Crypt
{
    public static String sign(String text, String key, String charset)
    {
        try
        {
            return DigestUtils.md5Hex((text + key).getBytes(charset));
        }
        catch (UnsupportedEncodingException e)
        {
            throw new SystemRuntimeException("解密出错", e);
        }
    }

    public static String sign(String text, String key)
    {
        return sign(text, key, CharsetUtils.UTF8);
    }

    public static byte[] hash(String text, String charset)
    {
        try
        {
            return DigestUtils.md5(text.getBytes(charset));
        }
        catch (UnsupportedEncodingException e)
        {
            throw new SystemRuntimeException("解密出错", e);
        }
    }

    public static byte[] hash(String text, Charset charset)
    {
        return DigestUtils.md5(text.getBytes(charset));
    }

    public static byte[] hash(String text)
    {
        return hash(text, CharsetUtils.UTF8);
    }

    public static boolean verify(String text, String sign, String key, String charset)
    {
        String mysign = sign(text, key, charset);
        return mysign.equals(sign);
    }

    public static boolean verify(String text, String sign, String key)
    {
        return verify(text, sign, key, CharsetUtils.UTF8);
    }

    // TEST
    public static void main(String[] args) throws UnsupportedEncodingException
    {
        // 需要加密的内容
        String str = "111111";
        String signed = MD5Crypt.sign(str, "1234567890qwertyuiopasdfghjklzxc");
        System.out.println(signed);
        boolean b = verify(null, signed, "1234567890qwertyuiopasdfghjklzxc");
        System.out.println(b);
    }
}
